package com.fayuan.nocv.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fayuan.nocv.entity.*;
import com.fayuan.nocv.service.DepartmentService;
import com.fayuan.nocv.service.RoleService;
import com.fayuan.nocv.service.UserService;
import com.fayuan.nocv.service.OfficeService;
import com.fayuan.nocv.utils.AliyunOSSUtil;
import com.fayuan.nocv.vo.DataView;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private RoleService roleService;

    @PostMapping("/file/uploadFile")
    @ResponseBody
    public Map<String, Object> updateIcon(MultipartFile file, HttpSession session){

        String s = AliyunOSSUtil.uploadFileAvatar(file);

        User user = (User) session.getAttribute("user");
        user.setImg(s);
        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("data",map2);
        map2.put("src",s);
        userService.updateById(user);
        session.setAttribute("user",user);
        return map;
    }

    @GetMapping("/login/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) {
        //生成验证码图片
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(116,36,4,10);
        //放到session中
        session.setAttribute("code",captcha.getCode());
        //输出验证码图片
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            captcha.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @PostMapping("/login")
    @ResponseBody
    public DataView login(String username,String password,String code,HttpSession session) {

        //shiro登录
        Subject subject = SecurityUtils.getSubject();
        DataView dataView = new DataView();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        User user = null;
        try {
        subject.login(token);
        user = (User) subject.getPrincipal();
        Object code1 = session.getAttribute("code");

            if (!user.equals(null)&&code.equals(code1.toString())){
                    dataView.setCode(200);
                    dataView.setMsg("登录成功");
                }else if (!code.equals(code1.toString())){
                    dataView.setCode(100);
                    dataView.setMsg("验证码错误");
                }
        } catch (Exception e) {
           dataView.setCode(100);
           dataView.setMsg("账号密码错误");
        }
        if (user!=null) {
            User byId = userService.getById(user.getId());
            session.setAttribute("user", byId);
        }
        return dataView;
    }

    @GetMapping("/logout")
    public String logout(){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @GetMapping("/loadAllUser")
    @ResponseBody
    public DataView loadAllUser(UserVo userVo){
        QueryWrapper<User>wrapper = new QueryWrapper<>();
        IPage<User>page = new Page<>(userVo.getPage(),userVo.getLimit());
        if (userVo.getUsername()!=null){
            wrapper.like("username",userVo.getUsername());
        }if (userVo.getPhone()!=null){
            wrapper.like("phone",userVo.getPhone());
        }
        IPage<User>page1 = userService.page(page,wrapper);

        List<User> records = page1.getRecords();

        for (User record : records) {
            if (record.getSex().equals(1)){
               record.setSexString("男");
           }else {
               record.setSexString("女");
           }
        }

        for (User record : records) {
            if (record.getDepartmentId()!=null){
                String name = departmentService.getById(record.getDepartmentId()).getName();
                record.setDepartmentName(name);
            }

            if (record.getOfficeId()!=null){
                String name = officeService.getById(record.getOfficeId()).getName();
                record.setOfficeName(name);
            }
        }

        return new DataView(page1.getTotal(),page1.getRecords());
    }

    @PostMapping("/addUser")
    @ResponseBody
    public DataView addUser(User user){
        String password = user.getPassword();

        DataView dataView = new DataView();

        userService.save(user);
        dataView.setCode(200);
        dataView.setMsg(user.getUsername()+"添加成功");
        return dataView;
    }
    @PostMapping("/updateUser")
    @ResponseBody
    public DataView updateUser(User user){
        userService.updateById(user);
        DataView dataView = new DataView();
        dataView.setCode(200);
        User user1 = userService.getById(user.getId());
        dataView.setMsg(user1.getUsername()+"修改成功");
        return dataView;
    }

    @PostMapping("/changePassword")
    @ResponseBody
    public DataView changePassword(User user,String newPwdOne,String newPwdTwo){

        User byId = userService.getById(user.getId());
        if (StringUtils.equals(byId.getPassword(),user.getPassword())
            &&StringUtils.equals(newPwdOne,newPwdTwo)){
            user.setPassword(newPwdOne);
            userService.updateById(user);
            DataView dataView = new DataView();
            dataView.setMsg("用户重置密码成功");
            dataView.setCode(200);
            return dataView;
        }
        if (!StringUtils.equals(newPwdOne,newPwdTwo)){
            DataView dataView = new DataView();
            dataView.setMsg("确认密码和新密码不一致");
            dataView.setCode(100);
            return dataView;
        }
        DataView dataView = new DataView();
        dataView.setMsg("旧密码不正确");
        dataView.setCode(100);
        return dataView;
    }

    @PostMapping("/deleteUser/{id}")
    @ResponseBody
    public DataView deleteUser(@PathVariable("id") Integer id){
        userService.removeById(id);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("删除成功");
        return dataView;
    }

    @GetMapping("/listAllDepartment")
    @ResponseBody
    public List<Department>listAllDepartment(){
        List<Department> list = departmentService.list();
        return list;
    }

    @GetMapping("/listAllOffice")
    @ResponseBody
    public List<Office>listAllOffice(){
        List<Office> list = officeService.list();
        return list;
    }
    @PostMapping("/resetPwd/{id}")
    @ResponseBody
    public DataView resetpwd(@PathVariable("id") Integer id){
        User byId = userService.getById(id);

        byId.setPassword("123456");

        userService.updateById(byId);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("密码重置成功");
        return dataView;
    }
    @GetMapping("/initRoleByUserId")
    @ResponseBody
    public DataView initRoleByUserId(Integer id){
        //查询所有角色
        List<Map<String, Object>> maps = roleService.listMaps();
        //查询当前登录用户拥有的角色
        List<Integer> roleIds = roleService.queryUserRoleById(id);
        //让前端变为选中状态
        for (Map<String, Object> map : maps) {
            Boolean LAY_CHECKED = false;
            Integer roleId = (Integer) map.get("id");
            for (Integer rid : roleIds) {
                if (rid.equals(roleId)){
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED);
        }
        return new DataView(Long.valueOf(maps.size()),maps);
    }

    @PostMapping("/saveUserRole")
    @ResponseBody
    public DataView saveRolePermission(Integer uid,Integer[] rids){
        //1.根据rid删除之前所有mid的权限
        roleService.deleteUserRoleByUId(uid);
        if (rids!=null && rids.length>0){
            for (Integer rid : rids){
                roleService.saveUserRole(uid,rid);
            }
        }
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("角色权限分配成功");
        return dataView;
    }
}
